$(document).ready(function(){

	$("#sub").click(function(){
		var userSum = parseInt($("#userSum").val());
		if(userSum > 0){
			$("#userSum").prop("value",userSum-1);
			var single_price = $("#single_price").text();
			var sum_price = parseFloat(single_price * (userSum-1)).toFixed(1);
			$("#total_price").text(sum_price);
		}		
	});
		
	
	$("#userSum").keyup(function(){
		listener();
	});
	
	$("#userSum").blur(function(){
		listener();
	});	
		
	function listener(){
		var regx = /^[1-9]+$/;
		var userSum = $("#userSum").val();
		var t = regx.test( userSum );
		if(!t){
			$("#userSum").prop("value","");
			$("#total_price").text("0.0");
		}else{
			var saleSum = parseFloat($("#saleSum").text());
			var single_price = parseFloat($("#single_price").text()).toFixed(1);
			if(userSum <= saleSum){
				var sum_price = parseFloat(single_price * userSum).toFixed(1);
				$("#total_price").text(sum_price);
			}else{
				$("#userSum").prop("value","");
				$("#total_price").text("0");
				alert("数量超出库存!请重新选择！");
			}	
		}
	}
	
	
	
	$("#add").click(function(){
		var userSum = parseInt($("#userSum").val());	
		var single_price = parseFloat($("#single_price").text()).toFixed(1);
		
		if(isNaN(userSum)){
			$("#userSum").prop("value",1);
			$("#total_price").text(single_price);
		}else{			
			var saleSum = parseInt($("#saleSum").text());
			if(userSum < saleSum){
				$("#userSum").prop("value",userSum+1);
				var sum_price = parseFloat(single_price * (userSum+1)).toFixed(1);
				$("#total_price").text(sum_price);
			}else{
				$("#userSum").prop("value","");
				$("#total_price").text("0");
				alert("数量超出库存!请重新选择！");
			}			
		}		
	});	
	
	//立即购买
	$("#justbuy").click(function(){
		var userSum = parseInt($("#userSum").val());
		if(userSum == 0 || isNaN(userSum)){
			alert("请添加数量！");
		}else{
			var userSum = parseInt($("#userSum").val());
			var saleSum = parseInt($("#saleSum").text());
			if(userSum <= saleSum){
				$("#form").submit();
			}else{
				$("#userSum").prop("value","");
				$("#total_price").text("0");
				alert("数量超出库存!请重新选择！");
			}		
		}				
	});
	
});